package com.fh.shop.api.recipient.biz;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fh.shop.api.common.ResponseEnum;
import com.fh.shop.api.common.ServerResponse;
import com.fh.shop.api.common.SystemConstant;
import com.fh.shop.api.recipient.mapper.IRecipientMapper;
import com.fh.shop.api.recipient.po.Recipient;
import com.fh.shop.api.util.KeyUtil;
import com.fh.shop.api.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service("recipientService")
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class IRecipientServiceImpl implements IRecipientService {

    @Autowired
    private IRecipientMapper recipientMapper;

    @Override
    public ServerResponse addRecipient(Recipient recipient) {
        // 验证
        // 非空验证

        // 电话格式的验证

        // 逻辑
        recipientMapper.insert(recipient);
        // 清缓存
        Long memberId = recipient.getMemberId();
        RedisUtil.delete(KeyUtil.buildRecipientKey(memberId));
        return ServerResponse.success();
    }

    @Override
    @Transactional(readOnly = true)
    public ServerResponse findList(Long id) {
        String recipientKey = KeyUtil.buildRecipientKey(id);
        String recipientListJson = RedisUtil.get(recipientKey);
        if (StringUtils.isNotBlank(recipientListJson)) {
//            log.info("从缓存查询会员:"+id+"对应的收件人列表");
            log.info("从缓存查询会员:{}对应的收件人{}列表", id, "===");
            List<Recipient> recipients = JSON.parseArray(recipientListJson, Recipient.class);
            return ServerResponse.success(recipients);
        }
        log.info("从数据库查询会员:{}的收件人列表", id);
        // 查询数据库
        QueryWrapper<Recipient> recipientQueryWrapper = new QueryWrapper<>();
        recipientQueryWrapper.eq("memberId", id);
        List<Recipient> recipients = recipientMapper.selectList(recipientQueryWrapper);
        // 存入缓存
        String recipientsJson = JSON.toJSONString(recipients);
        RedisUtil.set(recipientKey, recipientsJson);
        // 返回一份
        return ServerResponse.success(recipients);
    }

    @Override
    public ServerResponse deleteRecipient(Long id, Long memberId) {
        // 验证
        int count = getCount(memberId, id);
        if (count == 0) {
            // 会员id和收件人id不匹配
            return ServerResponse.error(ResponseEnum.RECIPIENT_ID_MEMBERID_MISMATCH);
        }
        recipientMapper.deleteById(id);
        RedisUtil.delete(KeyUtil.buildRecipientKey(memberId));
        return ServerResponse.success();
    }

    @Override
    @Transactional(readOnly = true)
    public ServerResponse findRecipient(Long id, Long memberId) {
        int count = getCount(memberId, id);
        if (count == 0) {
            // 会员id和收件人id不匹配
            return ServerResponse.error(ResponseEnum.RECIPIENT_ID_MEMBERID_MISMATCH);
        }
        // 先从缓存中查
        String recipientListJson = RedisUtil.get(KeyUtil.buildRecipientKey(memberId));
        if (StringUtils.isNotBlank(recipientListJson)) {
            List<Recipient> recipients = JSON.parseArray(recipientListJson, Recipient.class);
            Optional<Recipient> optionalRecipient = recipients.stream().filter(x -> x.getId().longValue() == id).findFirst();
            if (optionalRecipient.isPresent()) {
                Recipient recipient = optionalRecipient.get();
                return ServerResponse.success(recipient);
            }
        }
        // 查数据库【很少用的到】
        Recipient recipient = recipientMapper.selectById(id);
        return ServerResponse.success(recipient);
    }

    @Override
    public ServerResponse updateRecipient(Recipient recipient) {
        // 验证
        Long id = recipient.getId();
        Long memberId = recipient.getMemberId();
        int count = getCount(memberId, id);
        if (count == 0) {
            // 会员id和收件人id不匹配
            return ServerResponse.error(ResponseEnum.RECIPIENT_ID_MEMBERID_MISMATCH);
        }
        // 更新【待解决的问题】
        recipientMapper.updateById(recipient);
        RedisUtil.delete(KeyUtil.buildRecipientKey(memberId));
        return ServerResponse.success();
    }

    @Override
    public ServerResponse updateStatus(Long memberId, Long id) {
        // 验证
        int count = getCount(memberId, id);
        if (count == 0) {
            // 会员id和收件人id不匹配
            return ServerResponse.error(ResponseEnum.RECIPIENT_ID_MEMBERID_MISMATCH);
        }
        // 将 当前会员 对应的所有的收件人，更新为0【重置为0】
        resetStatus(memberId);
        // 更新收件人状态
        updateRecipientStatus(id);
        // 清除缓存
        RedisUtil.delete(KeyUtil.buildRecipientKey(memberId));
        // 响应
        return ServerResponse.success();
    }

    private void updateRecipientStatus(Long id) {
        Recipient recipient = new Recipient();
        recipient.setId(id);
        recipient.setStatus(SystemConstant.RECIPIENT_DEFAULT_ADDR);
        recipientMapper.updateById(recipient);
    }

    private void resetStatus(Long memberId) {
        Recipient recipient1 = new Recipient();
        recipient1.setStatus(SystemConstant.RECIPIENT_NOT_DEFAULT_ADDR);
        // 根据where条件进行更新
        // update 表 set status=0 where memberId = #{memberId}
        QueryWrapper<Recipient> recipientQueryWrapper = new QueryWrapper<>();
        recipientQueryWrapper.eq("memberId", memberId);
        recipientMapper.update(recipient1, recipientQueryWrapper);
    }

    private int getCount(Long memberId, Long id) {
        int count = 0;
        String recipientListJson = RedisUtil.get(KeyUtil.buildRecipientKey(memberId));
        if (StringUtils.isNotBlank(recipientListJson)) {
            // 通过缓存
            List<Recipient> recipients = JSON.parseArray(recipientListJson, Recipient.class);
            count = (int) recipients.stream().filter(x -> x.getId().longValue() == id.longValue()).count();
        } else {
            // 通过数据库
            // select count(*) from t_recipient where memberid=4 and id=5
            // 是否大于0
            QueryWrapper<Recipient> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("memberid", memberId);
            queryWrapper.eq("id", id);
            count = recipientMapper.selectCount(queryWrapper);
        }
        return count;
    }
}
